//! # RustCloud Prelude
//! 
//! 这个模块提供了RustCloud框架中最常用的类型和trait的便捷导入。
//! 通过 `use rustcloud::prelude::*;` 可以一次性导入所有常用的类型。

// 重新导出核心框架类型
pub use crate::{
    RustCloudBuilder,
    RustCloudFramework,
    RustCloudConfig,
    RustCloudResult,
    RustCloudError,
    VERSION,
    version,
};

// 重新导出配置相关类型
pub use crate::config::{
    ServiceConfig,
    ComponentConfig,
    NetworkConfig,
    MonitoringConfig,
    SecurityConfig,
    PerformanceConfig,
    RegistryConfig,
    LoadBalancerConfig,
    CircuitBreakerConfig,
    ProxyConfig,
    GatewayConfig,
    MetricsConfig,
    TracingConfig,
    LoggingConfig,
    HealthCheckConfig,
    TlsConfig,
    ConnectionPoolConfig,
    ThreadPoolConfig,
    MemoryConfig,
    // 🆕 配置广播相关类型
    ConfigBroadcastConfig,
    ConfigBroadcastListenerConfig,
    AutoRestartConfig,
};

// 重新导出构建器相关类型
pub use crate::builder::{
    ConfigurationBuilder,
    ServiceConfigBuilder,
    NetworkConfigBuilder,
};

// 重新导出框架核心类型
pub use crate::framework::{
    FrameworkState,
    HealthStatus,
    ComponentHealth,
};

// 重新导出rustcloud-core的核心类型
pub use rustcloud_core::{
    ServiceInstance,
    ServiceResult,
    ServiceError,
    Request,
    Response,
    RequestMetadata,
    ResponseMetadata,
};

// 重新导出注册中心相关类型
pub use rustcloud_registry::{
    ServiceRegistry,
    RegistryEvent,
    RegistryEventType,
    ServiceFilter,
    RegistryError,
    // 具体的注册中心实现
    MemoryRegistry,
    NacosRegistry,
    ConsulRegistry,
};

// 重新导出负载均衡相关类型
pub use rustcloud_loadbalancer::{
    LoadBalancerStrategy,
    LoadBalancerError,
    // 具体的负载均衡策略
    RoundRobinStrategy,
    RandomStrategy,
    WeightedRoundRobinStrategy,
    LeastConnectionsStrategy,
    ConsistentHashStrategy,
};

// 重新导出熔断器相关类型
pub use rustcloud_circuit_breaker::{
    CircuitBreaker,
    CircuitBreakerState,
    CircuitBreakerConfig as CBConfig,
    CircuitBreakerError,
    CircuitBreakerStats,
    FailureType,
    FallbackStrategy,
};

// 重新导出传输层相关类型
pub use rustcloud_transport::{
    Transport,
    TransportError,
    HttpTransport,
    TcpTransport,
    ConnectionPool,
    ConnectionManager,
};

// 重新导出代理相关类型
pub use rustcloud_proxy::{
    ServiceProxy,
    ProxyError,
    RequestInterceptor,
    ResponseInterceptor,
    RetryPolicy,
    CachePolicy,
};

// 重新导出指标相关类型
pub use rustcloud_metrics::{
    MetricsCollector,
    MetricType,
    MetricValue,
    Labels,
    MemoryMetricsCollector,
    PrometheusExporter,
    MetricsError,
};

// 重新导出日志相关类型
pub use rustcloud_logging::{
    Logger,
    LogLevel,
    LogEvent,
    LogFilter,
    LogAppender,
    FileAppender,
    ConsoleAppender,
    JsonFormatter,
    TextFormatter,
};

// 重新导出配置相关类型
pub use rustcloud_config::{
    ConfigManager,
    ConfigSource,
    ConfigError,
    DynamicConfig,
    ConfigWatch,
    // 🆕 配置广播相关类型
    ConfigBroadcaster,
    ConfigBroadcastListener,
    ConfigBroadcastManager,
    ConfigBroadcastEvent,
    ConfigBroadcastEventType,
    ServiceState,
    ServiceStatus,
    BroadcastStats,
};

// 重新导出网关相关类型（如果启用）
#[cfg(feature = "gateway")]
pub use rustcloud_gateway::{
    Gateway,
    GatewayError,
    Route,
    RouteMatch,
    RouteAction,
    Middleware,
    AuthMiddleware,
    RateLimitMiddleware,
    CorsMiddleware,
};

// 常用的异步trait
pub use async_trait::async_trait;

// 常用的序列化和反序列化trait
pub use serde::{Serialize, Deserialize};

// 常用的时间类型
pub use std::time::{Duration, Instant, SystemTime};
pub use chrono::{DateTime, Utc};

// 常用的集合类型
pub use std::collections::{HashMap, HashSet, BTreeMap, BTreeSet};

// 常用的同步原语
pub use std::sync::{Arc, Mutex};
pub use tokio::sync::{RwLock, Semaphore, broadcast, mpsc};

// 常用的错误处理类型
pub use anyhow::{Result as AnyResult, Error as AnyError, Context, bail};

// 常用的Future和Stream trait
pub use futures::{Future, Stream, StreamExt, FutureExt};

// 常用的网络类型
pub use std::net::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr};

// 便捷的构建器宏
/// 创建RustCloud服务构建器的便捷宏
#[macro_export]
macro_rules! service {
    ($name:expr) => {
        $crate::RustCloudBuilder::new($name)
    };
    ($name:expr, version = $version:expr) => {
        $crate::RustCloudBuilder::new($name).with_version($version)
    };
    ($name:expr, version = $version:expr, env = $env:expr) => {
        $crate::RustCloudBuilder::new($name)
            .with_version($version)
            .with_environment($env)
    };
}

/// 创建服务配置的便捷宏
#[macro_export]
macro_rules! service_config {
    ($name:expr) => {
        $crate::builder::ServiceConfigBuilder::new($name)
    };
    ($name:expr, $($key:ident = $value:expr),*) => {
        {
            let mut builder = $crate::builder::ServiceConfigBuilder::new($name);
            $(
                builder = builder.$key($value);
            )*
            builder
        }
    };
}

/// 创建网络配置的便捷宏
#[macro_export]
macro_rules! network_config {
    () => {
        $crate::builder::NetworkConfigBuilder::new()
    };
    ($($key:ident = $value:expr),*) => {
        {
            let mut builder = $crate::builder::NetworkConfigBuilder::new();
            $(
                builder = builder.$key($value);
            )*
            builder
        }
    };
}

/// 便捷的日志宏（基于tracing）
pub use tracing::{
    trace, debug, info, warn, error,
    instrument, span, Level, Span,
    event, field, fields,
};

/// 便捷的指标记录宏
#[macro_export]
macro_rules! record_metric {
    ($collector:expr, counter, $name:expr, $value:expr) => {
        $collector.record_counter($name, $value, std::collections::HashMap::new()).await
    };
    ($collector:expr, counter, $name:expr, $value:expr, $labels:expr) => {
        $collector.record_counter($name, $value, $labels).await
    };
    ($collector:expr, gauge, $name:expr, $value:expr) => {
        $collector.set_gauge($name, $value, std::collections::HashMap::new()).await
    };
    ($collector:expr, gauge, $name:expr, $value:expr, $labels:expr) => {
        $collector.set_gauge($name, $value, $labels).await
    };
}

/// 便捷的健康检查宏
#[macro_export]
macro_rules! health_check {
    ($framework:expr) => {
        $framework.health_check().await
    };
    ($framework:expr, $component:expr) => {
        {
            let health = $framework.health_check().await?;
            health.components.get($component).map(|c| c.status == "UP").unwrap_or(false)
        }
    };
}

/// 便捷的服务发现宏
#[macro_export]
macro_rules! discover {
    ($framework:expr, $service:expr) => {
        $framework.discover_services($service).await
    };
}

/// 便捷的负载均衡选择宏
#[macro_export]
macro_rules! select_instance {
    ($framework:expr, $service:expr) => {
        $framework.select_service_instance($service).await
    };
}

/// 便捷的配置获取宏
#[macro_export]
macro_rules! get_config {
    ($framework:expr) => {
        $framework.get_config()
    };
    ($framework:expr, $field:ident) => {
        &$framework.get_config().$field
    };
    ($framework:expr, $field:ident . $subfield:ident) => {
        &$framework.get_config().$field.$subfield
    };
}

/// 便捷的错误处理宏
#[macro_export]
macro_rules! service_error {
    ($msg:expr) => {
        $crate::ServiceError::ConfigurationError($msg.to_string())
    };
    ($kind:ident, $msg:expr) => {
        $crate::ServiceError::$kind($msg.to_string())
    };
}

/// 便捷的结果类型别名
pub type Result<T> = ServiceResult<T>;

/// 便捷的Box化Future类型
pub type BoxFuture<'a, T> = std::pin::Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// 便捷的服务实例创建函数
pub fn service_instance(
    name: &str,
    host: &str,
    port: u16,
) -> ServiceInstance {
    ServiceInstance {
        service_id: name.to_string(),
        host: host.to_string(),
        port,
        scheme: "http".to_string(),
        metadata: HashMap::new(),
        healthy: true,
        weight: 1.0,
        group: None,
        namespace: None,
        environment: None,
        cluster: None,
    }
}

/// 便捷的服务实例创建函数（带版本）
pub fn service_instance_with_version(
    name: &str,
    version: &str,
    host: &str,
    port: u16,
) -> ServiceInstance {
    let mut metadata = HashMap::new();
    metadata.insert("version".to_string(), version.to_string());
    
    ServiceInstance {
        service_id: name.to_string(),
        host: host.to_string(),
        port,
        scheme: "http".to_string(),
        metadata,
        healthy: true,
        weight: 1.0,
        group: None,
        namespace: None,
        environment: None,
        cluster: None,
    }
}

/// 便捷的标签创建函数
pub fn labels() -> HashMap<String, String> {
    HashMap::new()
}

/// 便捷的标签创建宏
#[macro_export]
macro_rules! labels {
    () => {
        std::collections::HashMap::new()
    };
    ($($key:expr => $value:expr),*) => {
        {
            let mut map = std::collections::HashMap::new();
            $(
                map.insert($key.to_string(), $value.to_string());
            )*
            map
        }
    };
}

/// 便捷的元数据创建宏（同labels）
#[macro_export]
macro_rules! metadata {
    () => {
        std::collections::HashMap::new()
    };
    ($($key:expr => $value:expr),*) => {
        {
            let mut map = std::collections::HashMap::new();
            $(
                map.insert($key.to_string(), $value.to_string());
            )*
            map
        }
    };
}

// 重新导出常用的derive宏
pub use rustcloud_macros::{
    Service, Registry, LoadBalancer, CircuitBreaker,
    Metrics, Config,
};

/// 常用的测试工具（仅在测试时可用）
#[cfg(test)]
pub mod test_utils {
    use super::*;
    
    /// 创建测试用的框架实例
    pub async fn test_framework(service_name: &str) -> RustCloudFramework {
        RustCloudBuilder::new(service_name)
            .with_port(0) // 使用随机端口
            .build()
            .await
            .unwrap()
    }
    
    /// 创建测试用的服务实例
    pub fn test_service_instance(name: &str) -> ServiceInstance {
        service_instance(name, "127.0.0.1", 8080)
    }
    
    /// 等待一段时间（用于异步测试）
    pub async fn wait_for(duration: Duration) {
        tokio::time::sleep(duration).await;
    }
}